﻿/********************************************************************************
    Copyright (C) Binod Nepal, Planet Earth Solutions Pvt. Ltd., Kathmandu.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace MixNP.Web.Classifieds
{
    public partial class Search : MixNP.BusinessLayer.BaseClass
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string q = Pes.Utility.Conversion.TryCastString(Request.QueryString["q"]);

                if (!string.IsNullOrWhiteSpace(q))
                {
                    SearchTextBox.Text = q;
                    this.Page.Title = q;
                }

                string aspxErrorPath = Pes.Utility.Conversion.TryCastString(Request.QueryString["aspxerrorpath"]);
                string cat = Pes.Utility.Conversion.TryCastString(Request.QueryString["cat"]);
                string city = Pes.Utility.Conversion.TryCastString(Request.QueryString["city"]);
                decimal priceFrom = Pes.Utility.Conversion.TryCastDecimal(Request.QueryString["pricefrom"]);
                decimal priceTo = Pes.Utility.Conversion.TryCastDecimal(Request.QueryString["priceto"]);
                short sortBy = Pes.Utility.Conversion.TryCastShort(Request.QueryString["sort"]);
                int pageNumber = Pes.Utility.Conversion.TryCastShort(Request.QueryString["page"]);

                if (!string.IsNullOrWhiteSpace(aspxErrorPath))
                {
                    q = Pes.Utility.Conversion.GetSearchAlias(aspxErrorPath).Replace("+", " ");
                    SearchTextBox.Text = q;
                    SearchLiteral.Text = "Error 404 - Page Not Found";
                    Literal404.Text = "The page <a href=\"#\">" + Pes.Utility.PageUtility.GetCurrentDomainName() + aspxErrorPath + "</a> was not found on server.";

                }

                if (!string.IsNullOrWhiteSpace(cat))
                {
                    CategoryDropDownList.SelectedValue = cat;
                }

                if (!string.IsNullOrWhiteSpace(city))
                {
                    CityDropDownList.SelectedValue = city;
                }

                if (priceTo > priceFrom)
                {
                    if (priceFrom > 0)
                    {
                        PriceStartTextBox.Text = priceFrom.ToString("G29");
                        PriceEndTextBox.Text = priceTo.ToString("G29");
                    }
                }

                SortByDropDownList.SelectedValue = sortBy.ToString();

                this.ShowSearchResults(q, Pes.Utility.Conversion.TryCastShort(city), Pes.Utility.Conversion.TryCastInteger(cat), priceFrom, priceTo, sortBy, pageNumber);
            }

        }

        private void ShowSearchResults(string query, short cityId, int categoryId, decimal priceFrom, decimal priceTo, short sort, int pageNumber)
        {
            string strConn = ConfigurationManager.ConnectionStrings["PESConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(strConn);

            System.Data.SqlClient.SqlCommand Cmd = new System.Data.SqlClient.SqlCommand("dbo.Search", cn);
            Cmd.CommandType = System.Data.CommandType.StoredProcedure;
            System.Data.SqlClient.SqlDataReader dr;

            bool hasRows = false;

            if (priceFrom.Equals(decimal.MinValue)) { priceFrom = 0; }
            if (priceTo.Equals(decimal.MinValue)) { priceTo = 0; }
            if (cityId.Equals(short.MinValue)) { cityId = 0; }
            if (sort.Equals(short.MinValue)) { sort = 0; }
            if (pageNumber.Equals(int.MinValue)) { pageNumber = 0; }
            if (categoryId.Equals(int.MinValue)) { categoryId = 0; }

            if (pageNumber.Equals(0)) { pageNumber = 1; }

            Cmd.Parameters.Add("@PageNumber", System.Data.SqlDbType.Int).Value = pageNumber;
            Cmd.Parameters.Add("@Query", System.Data.SqlDbType.NVarChar, 128).Value = query;
            Cmd.Parameters.Add("@CategoryId", System.Data.SqlDbType.Int).Value = categoryId;
            Cmd.Parameters.Add("@PriceFrom", System.Data.SqlDbType.Money).Value = priceFrom;
            Cmd.Parameters.Add("@PriceTo", System.Data.SqlDbType.Money).Value = priceTo;
            Cmd.Parameters.Add("@CityId", System.Data.SqlDbType.SmallInt).Value = cityId;
            Cmd.Parameters.Add("@Order", System.Data.SqlDbType.SmallInt).Value = sort;

            Cmd.Parameters.Add("@ItemCount", System.Data.SqlDbType.Int).Direction = System.Data.ParameterDirection.Output;

            cn.Open();
            dr = Cmd.ExecuteReader();


            CardRepeater.DataSource = dr;
            CardRepeater.DataBind();
            hasRows = dr.HasRows;
            dr.Close();
            cn.Close();

            Int32 _totalRecords = Convert.ToInt32(Cmd.Parameters["@ItemCount"].Value);

            TopPager.RecordCount = _totalRecords;
            TopPager.PageSize = 20;

            BottomPager.RecordCount = _totalRecords;
            BottomPager.PageSize = 20;

            TopPager.ShowDisabledButtons = false;
            BottomPager.ShowDisabledButtons = false;
            if (_totalRecords.Equals(0) || !hasRows)
            {
                TopPager.Visible = false;
                BottomPager.Visible = false;
                NothingLiteral.Text = "<h2>Nothing found. :(</h2>";
            }

        }

        protected void SearchButton_Click(object sender, EventArgs e)
        {
            string q = HttpUtility.UrlEncode(SearchTextBox.Text);
            string cat = CategoryDropDownList.SelectedItem.Value;
            string city = CityDropDownList.SelectedValue;
            decimal priceFrom = Pes.Utility.Conversion.TryCastDecimal(PriceStartTextBox.Text);
            decimal priceTo = Pes.Utility.Conversion.TryCastDecimal(PriceEndTextBox.Text);
            string sortBy = SortByDropDownList.SelectedValue;

            string url = "~/search/?q=" + q;

            url += "&sort=" + sortBy;

            if (!cat.Equals("0"))
            {
                url += "&cat=" + cat;
            }

            if (!city.Equals("0"))
            {
                url += "&city=" + city;
            }

            if (priceTo > priceFrom)
            {
                if (priceFrom >= 0)
                {
                    url += "&pricefrom=" + priceFrom.ToString("G29") + "&priceto=" + priceTo.ToString("G29");
                }
            }

            Response.Redirect(url, true);
        }
    }
}